<template>
  <div>
    <h1>WeChat JS-SDK Example</h1>
    <button @click="getLocation">Get Location</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import VConsole from "vconsole";

// 初始化 vConsole
const vConsole = new VConsole();

// 动态加载微信 JS-SDK
const loadWeChatSDK = () => {
  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = "https://res.wx.qq.com/open/js/jweixin-1.2.0.js";
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
};

const wechatAPIs = [
  "onMenuShareAppMessage",
  "onMenuShareWechat",
  "startRecord",
  "stopRecord",
  "onVoiceRecordEnd",
  "playVoice",
  "pauseVoice",
  "stopVoice",
  "onVoicePlayEnd",
  "uploadVoice",
  "downloadVoice",
  "chooseImage",
  "previewImage",
  "uploadImage",
  "downloadImage",
  "getNetworkType",
  "openLocation",
  "getLocation",
  "hideOptionMenu",
  "showOptionMenu",
  "hideMenuItems",
  "showMenuItems",
  "hideAllNonBaseMenuItem",
  "showAllNonBaseMenuItem",
  "closeWindow",
  "scanQRCode",
  "chooseVideo",
  "uploadVideo",
  "downloadVideo",
  "agentConfig",
  "getStepCount",
  "getAllPhoneContacts",
  "addCalendarEvent",
  "showWatermark",
  "launch3rdApp",
  "getInstallState",
  "openUserProfile",
  "selectEnterpriseContact",
  "bioassayAuthentication",
  "openUrl",
  "request3rdApp",
  "openChatWithMsg",
  "shareWechatMessage",
  "onMenuShareTimeline",
  "getLocalImgData",
  "previewFile",
  "startRecordVoiceBuffer",
  "onRecordBufferReceived",
  "stopRecordVoiceBuffer",
  "translateVoice",
  "startWifi",
  "stopWifi",
  "connectWifi",
  "getWifiList",
  "onGetWifiList",
  "onWifiConnected",
  "getConnectedWifi",
  "openBluetoothAdapter",
  "closeBluetoothAdapter",
  "getBluetoothAdapterState",
  "onBluetoothAdapterStateChange",
  "startBluetoothDevicesDiscovery",
  "stopBluetoothDevicesDiscovery",
  "getBluetoothDevices",
  "onBluetoothDeviceFound",
  "getConnectedBluetoothDevices",
  "createBLEConnection",
  "closeBLEConnection",
  "onBLEConnectionStateChange",
  "getBLEDeviceServices",
  "getBLEDeviceCharacteristics",
  "readBLECharacteristicValue",
  "writeBLECharacteristicValue",
  "notifyBLECharacteristicValueChange",
  "onBLECharacteristicValueChange",
  "startBeaconDiscovery",
  "stopBeaconDiscovery",
  "getBeacons",
  "onBeaconUpdate",
  "onBeaconServiceChange",
  "setClipboardData",
  "getClipboardData",
  "startAutoLBS",
  "stopAutoLBS",
  "onLocationChange",
  "onHistoryBack",
  "onUserCaptureScreen",
  "hideWatermark",
  "checkIsSupportSoterAuthentication",
  "checkIsSoterEnrolledInDevice",
  "startSoterAuthentication",
  "ocr",
  "launchMiniprogram",
  "createDoc",
  "wedocSelectDoc",
  "startMeeting",
  "wedriveSelectDir",
  "wedriveSelectFile",
  "checkSchedule",
];

// 获取当前页面的 URL
const url = window.location.href;

// 定义一个 ref 来存储微信 JS-SDK 的配置状态
const isWxConfigReady = ref(false);

// 获取签名参数并配置微信 JS-SDK
const getWeChatSignature = async () => {
  try {
    const response = await axios.get(
      `http://localhost:3000/get-wechat-signature?url=${encodeURIComponent(
        url
      )}`
    );
    const data = response.data;

    wx.config({
      beta: true, // 调用wx.invoke形式的接口值时，该值必须为true。
      //   debug: true, // 开启调试模式, 调用的所有api的返回值会在客户端alert出来
      appId: data.appId, // 必填，企业微信的corpID
      timestamp: data.timestamp, // 必填，生成签名的时间戳
      nonceStr: data.nonceStr, // 必填，生成签名的随机串
      signature: data.signature, // 必填，签名
      jsApiList: [
        "getLocation",
        "getNetworkType",
        "openLocation",
        "checkJsApi",
        "getLocalImgData",
        "openChatWithMsg",
      ], // 必填，需要使用的JS接口列表
    });

    wx.ready(() => {
      console.log("wx.ready called");
      wx.checkJsApi({
        jsApiList: wechatAPIs,
        success: (res) => {
          console.log(res);
        },
        fail: (err) => {
          console.error("Location failed:", err);
        },
      });
    });

    wx.error((res) => {
      console.error("wx.config error:", res);
      alert("wx.config error: " + JSON.stringify(res));
    });
  } catch (error) {
    console.error("Error fetching signature:", error);
  }
};

// 在组件挂载时获取签名参数
onMounted(async () => {
  try {
    await loadWeChatSDK();
    getWeChatSignature();
  } catch (error) {
    console.error("Error loading WeChat SDK:", error);
  }
});

// 获取地理位置
const getLocation = () => {
  wx.invoke(
    "openChatWithMsg",
    {
      userIds: "v_yuexhe;abctest;abctest2;abctest2", //参与会话的企业成员列表，格式为userid1;userid2;...，用分号隔开。
      groupName: "讨论组", // 非必填，会话名称。单聊时该参数传入空字符串''即可。
      chatId: "", //新建会话时，chatId必须为空串
      msg: {
        title: "008051528", // 消息标题
        desc: "008051528", // 消息描述
        link: "", // 消息链接
        imgUrl: "", // 消息封面
      },
      success: (res) => {
        console.log(res);
      },
      fail: (res) => {
        console.error(res);
      },
    },
    function (res) {
      console.log(res);
      if (res.err_msg == "openChatWithMsg:ok") {
        var chatId = res.chatId;
        console.log(res);
      }
    }
  );
};
</script>
